<style lang="less" scoped>
.container {
  min-height: 100vh;
  background: rgba(97, 255, 227, .08);
}
.echarts {
  height: 250px;
}
// selecet-bar
.selecet-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 10px 0 10px;
  padding-bottom: 0;
  .calendar {
    font-size: 28px;
    color: #1d363c;
  }
  .device {
    width: 105px;
    height: 30px;
    padding: 0 5px 0 10px;
    background: #1d363c;
    border-radius: 18px;
    color: #8b93a6;
    font-size: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    overflow: hidden;
    .text {
      flex: 1;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .iconfont {
      color: #8b93a6;
      font-size: 14px;
      transition: all .3s;
      &.active {
        transform: rotate(180deg);
      }
    }
  }
}
// popup
.popup-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  .popup-tit {
    font-size: 15px;
    height: 46px;
    line-height: 50px;
    color: #8b93a6;
  }
  .popup-content {
    display: flex;
    flex: 1;
    overflow: hidden;
    // 加载文案
    .vant-list-text {
      font-size: 12px;
    }
    .device {
      width: 150px;
      height: 100%;
      background: #f7f8fa;
      text-align: left;
      overflow-y: auto;
      font-size: 14px;
      color: #5e5e5e;
      .device-item {
        padding: 8px 5px 8px 10px;
        position: relative;
        &::before {
          position: absolute;
          left: 0;
          top: 50%;
          transform: translate3d(0, -50%, 0);
          display: block;
          content: ' ';
          width: 3px;
          height: 100%;
          background: transparent;
        }
        &.active {
          background: #fff;
          color: rgb(19, 194, 194);
          &::before {
            background: rgb(19, 194, 194);
          }
        }
      }
    }
    .subdevice-list {
      flex: 1;
      overflow: hidden;
      font-size: 14px;
      color: #8b93a6;
      .subdevice-item {
        text-align: left;
        padding: 8px 12px;
        &.active {
          color: rgb(19, 194, 194);
        }
      }
    }
  }
}
</style>

<template>
  <div class="container">
    <div class="selecet-bar">
      <div class="calendar iconfont icon-calendar-fill" @click="calendarShow = true"/>
      <div class="device" @click="popupShow = !popupShow">
        <span class="text">{{query.name}}</span>
        <i :class="`iconfont icon-caret-down ${popupShow && 'active'}`"/>
      </div>
    </div>
    <!-- echarts -->
    <div class="charts-list" v-if="query.nodeId">
      <div class="echarts" ref="power"/>
      <div class="echarts" ref="current"/>
      <div class="echarts" ref="voltageWires"/>
      <div class="echarts" ref="energy"/>
    </div>
    <van-empty v-else description="选择设备查看数据" :image="require('./noResult.png')"/>
    <!-- 时间选择 -->
    <van-calendar
      v-model="calendarShow"
      :min-date="minDate"
      :max-date="maxDate"
      :default-date="defaultDate"
      :max-range="30"
      allow-same-day
      type="range"
      :show-title="false"
      color="#13c2c2"
      @confirm="changeDate"/>
    <!-- 设备选择 -->
    <van-popup
      v-model="popupShow"
      position="bottom"
      round
      :style="{ height: '70%' }" >
      <div class="popup-container">
        <div class="popup-tit van-hairline--bottom">设施设备选择</div>
        <div class="popup-content">
          <!-- 设施加载 -->
          <div class="device">
            <van-list
              v-model="sidebarLoading"
              :finished="sidebarFinished"
              finished-text="没有更多了"
              @load="sidebarLoad"
            >
              <div :class="`device-item van-ellipsis van-hairline--bottom ${sidebarId == item.id && 'active'}`" v-for="(item, index) in sidebarList" :key="index" @click="selectDevice(item)">{{item.name}}</div>
              <!-- 加载文案 -->
              <div class="vant-list-text" slot="loading">加载中...</div>
              <div class="vant-list-text" slot="finished"></div>
              <div class="vant-list-text" slot="error">加载失败</div>
            </van-list>
          </div>
          <!-- 电表加载 -->
          <div class="subdevice-list">
            <van-list
              v-model="subdeviceLoading"
              :finished="subdeviceFinished"
              finished-text="没有更多了"
              @load="subdeviceLoad"
            >
              <div :class="`subdevice-item van-ellipsis ${query.nodeId == item.id && 'active'}`" v-for="(item, index) in subdeviceList" :key="index" @click="selectSubDevice(item)">{{item.name}}</div>
              <van-empty v-if="!subdeviceList.length" description="暂时还没有数据" :image="require('./noResult.png')"/>
              <!-- 加载文案 -->
              <div class="vant-list-text" slot="loading">加载中...</div>
              <div class="vant-list-text" slot="finished"></div>
              <div class="vant-list-text" slot="error">加载失败</div>
            </van-list>
          </div>
        </div>
        </div>
    </van-popup>
  </div>
</template>

<script>
import {getPower, getCurrent, getVoltageWires, energy} from '@/api/charts'
import {getFacilityLists} from '@/api/equ'
import {getSubdeviceOpt} from '@/api/iot'
import {getCookie} from '@utils/cookie'
import './theme'
let minDate = moment().subtract(1, 'years')
let maxDate = moment()
let nowDay7 = moment().subtract(7, 'days')

export default {
  data() {
    return {
      subdeviceFinished: true,
      subdeviceLoading: false,
      subdeviceList: [],
      subdevicePage: 0,
      sidebarId: '',
      sidebarPage: 0,
      sidebarList: [],
      sidebarLoading: false,
      sidebarFinished: false,
      popupShow: false,
      calendarShow: false,
      minDate: minDate.toDate(),
      maxDate: maxDate.toDate(),
      defaultDate: [nowDay7.toDate(), maxDate.toDate()],
      options: {
        dataZoom: {
          type: 'inside',
          show: true,
          xAxisIndex: [0],
          start: 0,
          end: 100
        },
        grid: {
          top: 50,
          left: 50,
          right: 70,
          height: 160
        },
        toolbox: {
          show: true,
          showTitle: false,
          feature: {
            magicType: {
              type: ['line', 'bar', 'stack'],
            }
          },
        },
        tooltip: {
          trigger: 'axis',
          textStyle: {
            align: "left"
          },
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#8b93a6'
            }
          }
        }
      },
      query: {
        start: nowDay7.format('YYYY-MM-DD'),
        end: maxDate.format('YYYY-MM-DD'),
        name: '请选择设备',
        nodeId: '',
        nodeLevel: '',
        period: '',
        id: ''
      }
    }
  },
  mounted() {
    this.sidebarLoad(content => {
      if (content && content.length) this.sidebarId = content[0].id
      this.subdeviceLoad(result => {
        if (result && result.length) this.selectSubDevice(result[0])
      })
    })
    // this.initCharts()
  },
  methods: {
    // 初始化数据表
    initCharts() {
      this.$toast.loading({
        duration: 0,
        forbidClick: true,
        message: '加载中...'
      })
      axios.all([this.getPower(), this.getCurrent(), this.getVoltageWires(), this.energy()])
      .then((result) => {
        this.$toast.clear()
      })
      .catch(() => this.$toast.clear())
    },
    // 修改时间
    changeDate(e) {
      const [start, end] = e
      this.query.start = moment(start).format('YYYY-MM-DD')
      this.query.end = moment(end).format('YYYY-MM-DD')
      this.calendarShow = false
      this.initCharts()
    },
    // 总功率
    getPower() {
      getPower(this.query)
      .then((data) => {
        const {series} = data
        // 获取最大值，根据最大值决定左右距离
        let max = 0
        series.map(item => item.data && item.data.map(itemi => {if (itemi[1] > max) max = itemi[1] | 0}))
        echarts.init(this.$refs.power, 'threePhase').setOption(Object.assign(data, this.options, {grid: {left: 40, right: 80}}), true)
      })
    },
    // 电流
    getCurrent() {
      getCurrent(this.query)
      .then((data) => {
        const {series} = data
        // 获取最大值，根据最大值决定左右距离
        let max = 0
        series.map(item => item.data && item.data.map(itemi => {if (itemi[1] > max) max = itemi[1] | 0}))
        echarts.init(this.$refs.current, 'threePhase').setOption(Object.assign(data, this.options, {grid: {right: 20, left: Math.max(10 + `${max}`.length * 8, 20)}}), true)
      })
    },
    // 线电压
    getVoltageWires() {
      getVoltageWires(this.query)
      .then((data) => {
        const {series} = data
        // 获取最大值，根据最大值决定左右距离
        let max = 0
        series.map(item => item.data && item.data.map(itemi => {if (itemi[1] > max) max = itemi[1] | 0}))
        echarts.init(this.$refs.voltageWires, 'threePhase').setOption(Object.assign(data, this.options, {grid: {right: 20, left: Math.max(`${max / 1000}`.length * 8, 20)}}), true)
      })
    },
    // 线电压
    energy() {
      energy(this.query)
      .then((data) => {
        const {series} = data
        // 获取最大值，根据最大值决定左右距离
        let yAxisMax1 = 0
        let yAxisMax2 = 0
        series.map(item => {
          item.data && item.data.map(itemi => {
            item.yAxisIndex == 1 ? yAxisMax1 = Math.max(itemi[1] | 0, yAxisMax1) : yAxisMax2 = Math.max(itemi[1] | 0, yAxisMax2)
          })
        })
        echarts.init(this.$refs.energy, 'threePhase').setOption(Object.assign(data, this.options, {grid: {right: Math.max(`${yAxisMax1}`.length * 7, 55), left: Math.max(`${yAxisMax2 / 1000}`.length * 7, 20)}, legend: {itemWidth: 6}}), true)
      })
    },
    // 设备
    sidebarLoad(cb = () => {}) {
      const {sidebarPage} = this
      getFacilityLists({id: getCookie('org_id'), page: sidebarPage})
      .then(({content, totalPages}) => {
        this.sidebarList = content
        this.sidebarPage ++
        if (sidebarPage >= (totalPages - 1)) this.sidebarFinished = true
        cb(content)
      }).catch((err) => {
        
      });
    },
    // 电表加载
    subdeviceLoad(cb = () => {}) {
      const {subdevicePage, sidebarId} = this
      this.sidebarLoading = true
      getSubdeviceOpt({id: getCookie('org_id'), page: subdevicePage, id: sidebarId})
      .then((content) => {
        this.subdeviceList = content
        this.subdevicePage ++
        this.subdeviceFinished = true
        cb(content)
      }).catch((err) => {
          
      });
    },
    // 选择设备
    selectDevice(item) {
      const {id} = item
      const {sidebarId} = this
      if (id == sidebarId) return false
      this.sidebarId = id
      // 加载分类电表
      this.subdeviceFinished = false
      this.subdeviceLoading = false
      this.subdeviceList = []
      // this.subdeviceLoad()
    },
    // 选择电表
    selectSubDevice(item) {
      const {dtype, id, name} = item
      if (id == this.query.nodeId) return this.popupShow = false
      this.query.nodeId = id
      this.query.id = id
      this.query.nodeLevel = dtype
      this.query.name = name
      this.popupShow = false
      this.initCharts()
    }
  }
}
</script>